﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FlotasDesktop;
using System.Data.SqlClient;
using System.Globalization;
using System.Security.Cryptography;

namespace GestorDeFlotasDesktop.AbmUsuario
{
    public partial class AltaUsuario : Form
    {
        String conexion;
        public AltaUsuario()
        {
            InitializeComponent();
            Utils utils = new Utils();
            conexion = utils.cargarProperties();
            this.rolesDisponibles();
        }

        
        private void rolesDisponibles()
        {
            using (SqlConnection connection = new SqlConnection(conexion))
            {
                try
                {
                    using (SqlCommand command = new SqlCommand())
                    {
                        command.Connection = connection;
                        command.CommandType = System.Data.CommandType.StoredProcedure;
                        command.CommandText = "TEQUILASO.sp_cargarRolesHabilitados";
                        using (SqlDataAdapter adapter = new SqlDataAdapter(command))
                        {
                            DataTable dt = new DataTable();
                            adapter.Fill(dt);
                            rolesList.DataSource = dt;
                            rolesList.DisplayMember = "Nombre";
                            rolesList.ValueMember = "Id";
                            
                        }

                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

        }


        private void Alta_Click(object sender, EventArgs e)
        {
            using (SqlConnection connection = new SqlConnection(conexion))
            {
                try
                {
                    using (SqlCommand command = new SqlCommand())
                    {
                        if (userTextBox.Text.Length > 0 && passTextBox.Text.Length > 0 && rolesList.CheckedItems.Count != 0)
                        {
                            string sql = "select * from TEQUILASO.Usuario where Nombre = '" + this.userTextBox.Text + "'";
                                connection.Open();
                                command.Connection = connection;
                                command.CommandText = sql;
                                command.CommandType = CommandType.Text;

                                SqlDataReader reader = command.ExecuteReader();
                                if (reader.HasRows)
                                {
                                    MessageBox.Show("Ya existe el usuario que desea crear");
                                    return;
                                }
                                else
                                {
                                    connection.Close();
                                    connection.Open();
                                    command.CommandType = System.Data.CommandType.StoredProcedure;
                                    command.CommandText = "TEQUILASO.sp_altaUsuario";
                                    command.Parameters.AddWithValue("@Nombre", userTextBox.Text);
                                    command.Parameters.AddWithValue("@Password", this.crearContrasenia(passTextBox.Text));
                                    command.Parameters.AddWithValue("@Habilitado", true);
                                    command.ExecuteReader();
                                    connection.Close();
                               

                                    this.altaRolPorUsuario();
                                    this.Close();
                                }
                            
                            MessageBox.Show("Operacion realizada con exito");
                        }else
                        {
                            MessageBox.Show("Todos los datos son obligatorios");
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void altaRolPorUsuario()
        {

            using (SqlConnection connection1 = new SqlConnection(conexion))
            {
                try
                {
                    using (SqlCommand command1 = new SqlCommand())
                    {
                        foreach (DataRowView dr in rolesList.CheckedItems)
                        {
                            connection1.Open();
                            command1.Connection = connection1;
                            command1.CommandType = System.Data.CommandType.StoredProcedure;
                            command1.CommandText = "TEQUILASO.sp_rolPorUsuario";
                            command1.Parameters.AddWithValue("@Nombre", userTextBox.Text);
                            command1.Parameters.AddWithValue("@Id_Rol", Convert.ToInt32(dr[rolesList.ValueMember].ToString()));
                            command1.ExecuteReader();
                            command1.Parameters.Clear();
                            connection1.Close();
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void comboBoxRoles_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private String crearContrasenia(String contra)
        {
            SHA256 sha256 = new SHA256Managed();
            byte[] inputBytes = Encoding.UTF8.GetBytes(contra);
            byte[] hashedBytes = sha256.ComputeHash(inputBytes);
            StringBuilder hashedString = new StringBuilder();
            string cadenaHash;

            for (int i = 0; i < hashedBytes.Length; i++)
                hashedString.Append(hashedBytes[i].ToString("x2").ToLower());

            cadenaHash = hashedString.ToString();

            return cadenaHash;
        }

        private void rolesList_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

    }
}
